package com.boang.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/*
  @author: 13813
  @date: 2024/8/28 15:05
*/
@RestController
public class SentinelController {

    @RequestMapping("/st01")
    public String st01() {
        try (Entry entry = SphU.entry("HelloWorld")) {
            // 被保护的逻辑
            System.out.println("hello world");
        } catch (BlockException ex) {
            // 处理被流控的逻辑
//            System.out.println("blocked!");
            return "blocked";
        }
        return "ABC";
    }

    @RequestMapping("/initFlowRules")
    public void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(2);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    //    @SentinelResource(value = "st02", fallback = "st02Handler")
    @RequestMapping("/st02")
    public String st02() throws InterruptedException {
        Thread.sleep(5000);
        return "ABC";
    }

//    public String st02Handler(Throwable throwable) {
//        throwable.printStackTrace();
//        return "系统繁忙，稍后再试";
//    }

    @RequestMapping("/st03")
    public String st03(int id, String name) {
        return "ABC";
    }
}
